import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryWithdrawList,
  cancelWithdraw,
  queryWithdrawPrintDetail,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    cancel: Effect;
    fetchReceipt: Effect;
  };
  reducers: {
    save: Reducer;
    saveReceipt: Reducer;
    changeReceipt: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'logisCenterWithdrawList',

  state: {
    data: {
      list: [],
      count: 0,
    },
    receipt: {},
    hasReceipt: false,
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryWithdrawList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: data.body,
      });
    },
    * cancel({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(cancelWithdraw, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('取消成功');
        yield put({
          type: 'fetch',
          payload: search,
        });
      }
    },

    * fetchReceipt({ payload }, { call, put }) {
      const { logisName, expressName, ...query } = payload;
      const response = yield call(queryWithdrawPrintDetail, query);
      const data = fetchValidation(response);
      if (data) {
        if (data.code === 9) message.error(data.msg);
        const params = {
          ...data.body,
          logisName,
          expressName,
          startTime: payload.startTime,
          endTime: payload.endTime,
        };
        yield data && put({
          type: 'saveReceipt',
          payload: params,
        });
        yield data && put({
          type: 'changeReceipt',
          payload: data.code === 0,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },

    saveReceipt(state, { payload }) {
      return {
        ...state,
        receipt: payload,
      };
    },

    changeReceipt(state, { payload }) {
      return {
        ...state,
        hasReceipt: payload,
      };
    },
  },
};

export default Model;
